#! /bin/bash
# demo: bash multi_process.sh /path/to/T1

source /etc/profile;

# -----------------------------

tempfifo=$$.fifo        # $$表示当前执行文件的PID
pre_dir=$1           # 开始时间

if [ $# -eq 1 ]
then
    echo "Begin Processing!"
else
    echo "Error! Not enough params."
    echo "Sample: sh multi_process `/dir/to/data`"
    exit 2;
fi

# -----------------------------

trap "exec 1000>&-;exec 1000<&-;exit 0" 2
mkfifo $tempfifo
exec 1000<>$tempfifo
rm -rf $tempfifo

for ((i=1; i<=8; i++))
do
    echo >&1000
done

target_dir=$pre_dir"_processed"
if [ ! -d $target_dir ];then
    mkdir $target_dir
fi

for dir in $(ls $pre_dir)
do
    if [ -d $pre_dir"/"$dir ];then
        fil=$(ls $pre_dir"/"$dir)
        read -u1000
        {
            for sub_file in $fil
            do
                if [ -d $sub_file ];then
                    continue
                else
                    origin_file=$pre_dir"/"$dir"/"$sub_file;
                    cmd_str="recon-all -all -i "$origin_file" -s "$dir"_FS -sd "$target_dir" &";
                    echo "[CMD]: " $cmd_str;
                    eval $cmd_str;
                    break;
                fi
            done
            echo >&1000
        } &
    fi
done

wait
echo "done!!!!!!!!!!"
